#!/usr/bin/env python3
"""
实时系统监控脚本
监控UC系统各服务的运行状态
"""

import requests
import time
import json
import os
import sys
import threading
from datetime import datetime
import io
import psutil
import subprocess
from typing import Dict, List, Any

# 设置UTF-8编码
if sys.platform == "win32":
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# API配置
API_BASE_URL = "http://localhost:4000/api"
AI_API_URL = "http://localhost:5001"

def log_message(message: str):
    """记录日志消息"""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{timestamp}] {message}")
    sys.stdout.flush()

def check_port(port: int) -> bool:
    """检查端口是否被占用"""
    for conn in psutil.net_connections():
        if conn.laddr.port == port:
            return True
    return False

def get_service_status():
    """获取各服务状态"""
    status = {
        "timestamp": datetime.now().isoformat(),
        "services": {}
    }

    # 检查后端服务 (端口4000)
    if check_port(4000):
        try:
            response = requests.get(f"{API_BASE_URL}/health", timeout=2)
            if response.status_code == 200:
                data = response.json()
                status["services"]["backend"] = {
                    "status": "running",
                    "port": 4000,
                    "response_time": response.elapsed.total_seconds(),
                    "message": data.get("message", ""),
                    "version": data.get("data", {}).get("version", "unknown")
                }
            else:
                status["services"]["backend"] = {
                    "status": "error",
                    "port": 4000,
                    "error": f"HTTP {response.status_code}"
                }
        except Exception as e:
            status["services"]["backend"] = {
                "status": "error",
                "port": 4000,
                "error": str(e)
            }
    else:
        status["services"]["backend"] = {
            "status": "stopped",
            "port": 4000
        }

    # 检查AI推理服务 (端口5001)
    if check_port(5001):
        try:
            response = requests.get(f"{AI_API_URL}/health", timeout=2)
            if response.status_code == 200:
                data = response.json()
                status["services"]["ai_inference"] = {
                    "status": "running",
                    "port": 5001,
                    "response_time": response.elapsed.total_seconds(),
                    "model_loaded": data.get("model_loaded", False),
                    "device": data.get("device", "unknown")
                }
            else:
                status["services"]["ai_inference"] = {
                    "status": "error",
                    "port": 5001,
                    "error": f"HTTP {response.status_code}"
                }
        except Exception as e:
            status["services"]["ai_inference"] = {
                "status": "error",
                "port": 5001,
                "error": str(e)
            }
    else:
        status["services"]["ai_inference"] = {
            "status": "stopped",
            "port": 5001
        }

    # 检查前端服务 (端口8101)
    if check_port(8101):
        status["services"]["frontend"] = {
            "status": "running",
            "port": 8101
        }
    else:
        status["services"]["frontend"] = {
            "status": "stopped",
            "port": 8101
        }

    # 检查数据库 (MySQL端口3306)
    if check_port(3306):
        status["services"]["database"] = {
            "status": "running",
            "port": 3306
        }
    else:
        status["services"]["database"] = {
            "status": "stopped",
            "port": 3306
        }

    # 获取系统资源使用情况
    cpu_percent = psutil.cpu_percent(interval=0.5)
    memory = psutil.virtual_memory()
    disk = psutil.disk_usage('/')

    status["system"] = {
        "cpu_percent": cpu_percent,
        "memory_percent": memory.percent,
        "memory_used_gb": memory.used / (1024**3),
        "memory_total_gb": memory.total / (1024**3),
        "disk_percent": disk.percent,
        "disk_free_gb": disk.free / (1024**3)
    }

    return status

def monitor_continuously(interval: int = 5, duration: int = 60):
    """持续监控系统状态"""
    log_message(f"开始监控系统状态，间隔{interval}秒，持续{duration}秒")
    log_message("="*60)

    start_time = time.time()
    monitoring_data = []

    while time.time() - start_time < duration:
        status = get_service_status()
        monitoring_data.append(status)

        # 打印状态
        print("\n" + "-"*60)
        print(f"系统状态 - {status['timestamp']}")
        print("-"*60)

        for service_name, service_info in status["services"].items():
            service_emoji = "✓" if service_info["status"] == "running" else "✗" if service_info["status"] == "stopped" else "⚠"
            print(f"{service_emoji} {service_name}:")
            print(f"   状态: {service_info['status']}")
            print(f"   端口: {service_info['port']}")
            if "response_time" in service_info:
                print(f"   响应时间: {service_info['response_time']:.3f}s")
            if "error" in service_info:
                print(f"   错误: {service_info['error']}")

        print("\n系统资源:")
        print(f"   CPU使用率: {status['system']['cpu_percent']:.1f}%")
        print(f"   内存使用率: {status['system']['memory_percent']:.1f}% ({status['system']['memory_used_gb']:.1f}GB/{status['system']['memory_total_gb']:.1f}GB)")
        print(f"   磁盘使用率: {status['system']['disk_percent']:.1f}% (剩余: {status['system']['disk_free_gb']:.1f}GB)")

        time.sleep(interval)

    # 保存监控数据
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"system_monitor_{timestamp}.json"
    with open(filename, "w", encoding="utf-8") as f:
        json.dump(monitoring_data, f, indent=2, ensure_ascii=False)

    log_message(f"\n监控数据已保存到: {filename}")
    return monitoring_data

def quick_check():
    """快速检查服务状态"""
    log_message("快速服务状态检查")
    log_message("="*40)

    status = get_service_status()
    all_running = True

    for service_name, service_info in status["services"].items():
        if service_info["status"] == "running":
            log_message(f"✓ {service_name} (端口 {service_info['port']}) - 运行中")
        else:
            log_message(f"✗ {service_name} (端口 {service_info['port']}) - {service_info['status']}")
            all_running = False

    log_message("\n系统资源:")
    log_message(f"  CPU: {status['system']['cpu_percent']:.1f}%")
    log_message(f"  内存: {status['system']['memory_percent']:.1f}%")
    log_message(f"  磁盘: {status['system']['disk_percent']:.1f}%")

    if all_running:
        log_message("\n✓ 所有服务运行正常！")
    else:
        log_message("\n⚠ 部分服务未运行，请检查")

def main():
    """主函数"""
    if len(sys.argv) > 1 and sys.argv[1] == "monitor":
        # 持续监控模式
        interval = int(sys.argv[2]) if len(sys.argv) > 2 else 5
        duration = int(sys.argv[3]) if len(sys.argv) > 3 else 60
        monitor_continuously(interval, duration)
    else:
        # 快速检查模式
        quick_check()

if __name__ == "__main__":
    main()